using MediatR;
using RBAC.Domain.ProductionPlans;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ProductionPlans;
using RBAC.Interstructrue.Base;
using Dapper;

namespace RBAC.Read.Api.Application.Handler.ProductionPlans
{
    public class GetSalesTableCommandHandler : IRequestHandler<GetSalesTableCommands, APIResult<APIPaging<SalesTable>>>
    {
        private readonly IBaseRepository<SalesTable> salesRep;

        public GetSalesTableCommandHandler(IBaseRepository<SalesTable> salesRep)
        {
            this.salesRep = salesRep;
        }

        public Task<APIResult<APIPaging<SalesTable>>> Handle(GetSalesTableCommands request, CancellationToken cancellationToken)
        {
            try
            {
                var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
                var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

                var where = "IsDeleted = false";
                var param = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(request.SalesCode))
                {
                    where += " AND SalesCode LIKE @SalesCode";
                    param.Add("SalesCode", $"%{request.SalesCode}%");
                }
                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    where += " AND CustomerName LIKE @CustomerName";
                    param.Add("CustomerName", $"%{request.CustomerName}%");
                }
                if (request.ProcurementStatus.HasValue)
                {
                    where += " AND ProcurementStatus = @ProcurementStatus";
                    param.Add("ProcurementStatus", request.ProcurementStatus.Value);
                }

                var orderBy = "Id DESC";
                var (data, total) = salesRep.GetPaged(pageIndex, pageSize, where, orderBy, param);

                var paging = new APIPaging<SalesTable>
                {
                    PageDatas = data,
                    TotalCount = total
                };

                return Task.FromResult(new APIResult<APIPaging<SalesTable>>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = paging
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<APIPaging<SalesTable>>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = new APIPaging<SalesTable>()
                });
            }
        }
    }
}
